const sipUtils = require("../../../utils/sipUtils");
const log4js = require('../../../utils/logUtils');
const deviceCache = require("../../../db/deviceCache");
const logger = log4js.getLogger('sip');
const config = require("../../../db/config");

/**
 * 生成 bye 信令
 */
module.exports={
    generate (deviceId, channel) {
        if (!deviceId || !channel) {
            logger.warn('参数错误，deviceid=', deviceId, 'channel=', channel);
            return null;
        } else if (!deviceCache.registry[deviceId]) {
            logger.warn('设备未注册成功,可能是拉流代理添加的', deviceId);
            return null;
        } else if (!deviceCache.registry[deviceId].channels) {
            logger.warn('设备注册有问题，初始化未成功', deviceId);
            return null;
        }
        let channelInfo = deviceCache.registry[deviceId].channels[channel];
        if (!channelInfo) {
            logger.error('设备未注册');
            return null;
        }
        if (!channelInfo.invite) {
            logger.warn('没有记录播放信息', channelInfo);
            return null;
        }

        let cseq = {
            method: 'BYE',
            seq: channelInfo.invite.headers.cseq.seq + 1
        };
        let res = {
            method: cseq.method,
            uri: sipUtils.generateUri(channelInfo.deviceid, channel, null, deviceCache.registry[deviceId].sip_command_host, deviceCache.registry[deviceId].sip_command_port),
            version: config.sip.version,
            headers: {
                via: sipUtils.generateVia(channelInfo.protocol),
                from: Object.assign({}, channelInfo.invite.headers.from),
                to: Object.assign({}, channelInfo.invite.headers.to),
                'call-id': channelInfo.invite.headers['call-id'],
                cseq,
                'Max-Forwards': 70,
                'User-Agent': config.sip.useragent,
                contact: sipUtils.buildContact()
            }
        };

        if (deviceCache.registry.invites[channelInfo.invite.headers['call-id']]) {
            delete deviceCache.registry.invites[channelInfo.invite.headers['call-id']];
        }
        return res;
    },
}
